package com.wthink.hzgj.main.viewmodel

import android.app.Application
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.ViewModel
import com.wthink.hzgj.data.Result
import com.wthink.hzgj.data.domain.CheckinType
import com.wthink.hzgj.data.domain.SettingKey
import com.wthink.hzgj.data.repository.SettingWithCacheRepository
import com.wthink.hzgj.service.DevService
import com.wthink.hzgj.util.PreferencesUtils
import com.wthink.hzgj.util.toast
import java.math.BigDecimal
import java.text.SimpleDateFormat
import java.util.*

class CheckinViewModel : ViewModel() {

    val checkinType = MutableLiveData(CheckinType.SB)//0:上班，1:下班，2:签到

    val sbTime = MutableLiveData("")
    val xbTime = MutableLiveData("")
    val qdTime = MutableLiveData("")

    val userCode = MutableLiveData("")

    val settingRepository = SettingWithCacheRepository

    suspend fun action(): String? {
        val user = userCode.value!!
        val type = checkinType.value!!
        if (user.isEmpty()) {
            return "请输入员工工号"
        }

        val sbflag = sbTime.value!!
        val xbflag = xbTime.value!!

        if (!xbflag.isEmpty() && type.equals(CheckinType.SB)) {
            return "请勿重复上班签到"
        }

        val ret = DevService.checkin(
            settingRepository.findSetting(SettingKey.LINE)!!,
            user,
            type
        )
        if (ret is Result.Success) {
            PreferencesUtils.saveValue("name",user)
            val username = PreferencesUtils.getStringObject("name")
            android.util.Log.d("namenamename", username)

            val sdf = SimpleDateFormat("HH:mm")
            val mix = PreferencesUtils.getLong("mix")
            val nowTime : BigDecimal = BigDecimal(mix).add(BigDecimal(System.currentTimeMillis()))

            when (type) {
                CheckinType.SB -> sbTime.postValue(sdf.format(nowTime))
                CheckinType.XB -> xbTime.postValue(sdf.format(nowTime))
                CheckinType.QD -> qdTime.postValue(sdf.format(nowTime))
            }
            return null
        } else if (ret is Result.Error) {
            return ret.exception.message
        } else {
            return null
        }
    }

    fun switchType(type: CheckinType) {
        checkinType.value = type
    }
}